# -*- coding:utf-8 -*-
import os,sys
import re
import traceback
import time
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir))
import supeanut_config
from CommonLib.mylog import mylog
from CommonLib.db.MongoDBTool import MongoDBTool
from CommonLib.FileTool.CsvTool import CsvTool
from CommonLib.StockTool import StockTool


'''
作者：supeanut
创建时间：2016-xx-xx xx:xx:xx
功能描述：
    每日更新stockInfo到Mongo,仅stock 无index
相关配置：
	supeanut_config.XXX
历史改动：
	2016-xx-xx: xxxxxx
'''
class StockInfoSend:
	# init what
	def __init__(self):
		self.mongo = MongoDBTool()
		self.csvtool = CsvTool()
		self.db_name = supeanut_config.MONGO_DB
		self.coll_stockinfo = supeanut_config.MONGO_COLL_STOCKINFO
		self.csv_path = supeanut_config.STOCKINFO_CSV_PATH
		self.csv_file = supeanut_config.STOCKINFO_CSV_FILE
		self.stock_obj = StockTool()
	

	# 更新StockInfo 
	def upsert_date(self, ):
		log = mylog('StockInfoSend.upsert_date', None)
		flag, msg = self.mongo.conn(self.db_name, self.coll_stockinfo)
		if flag is False:
			return False, msg
		flag, records = self.csvtool.read_csv(self.csv_path, self.csv_file)
		if flag is False:
			return False, 'read file %s failed'%self.csv_file
		for record in records:
			code = record[0].decode('utf-8')
			doc = {}
			doc['market_prefix'] = (self.stock_obj.get_stock_market(code)).decode('utf-8')
			doc['board'] = record[1].decode('utf-8')
			doc['stock_name'] = record[2].decode('utf-8')
			doc['status'] = record[4].decode('utf-8')
			doc['guben'] = record[5].decode('utf-8')
			doc['liutong'] = record[6].decode('utf-8')
			doc['s_date'] = record[7].decode('utf-8')
			doc['e_date'] = record[8].decode('utf-8')
			update_suc = False
			while not update_suc:
				try:
					self.mongo.coll.update_one({u'code':code},\
											{'$set':doc}, upsert = True)
				except:
					flag, msg = self.mongo.conn(self.db_name, self.coll_stockinfo)
					if flag is False:
						return False, traceback.format_exc()
					else:
						continue
				update_suc = True
		return True, 'suc'

if __name__ == '__main__':
	obj = StockInfoSend()
	print obj.upsert_date()
